//
//  ARIndexViewController.swift
//  AquaRaft
//
//  Created by 何启亮 on 2024/4/2.
//

import UIKit
import SnapKit
import AttributedString
import JKSwiftExtension

class ARIndexViewController: ARBaseViewController {

    // MARK: - Private property
    
    private static let cellReuseId = "AR.indexViewController.workCellRuseId"
    
    private let viewModel: ARIndexViewModel = ARIndexViewModel()
    private var viewScrolling = false
    
    private static let firstLoginUserKey = "ar.firstLoginUserListKey"
    private var hasShowAlert = false
    
    // MARK: - LifeCycle
    
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
        
        self.fd_prefersNavigationBarHidden = true
    }
    
    override init() {
        super.init()
        
        self.fd_prefersNavigationBarHidden = true
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        self.setupUI()
        self.refreshData()
        
        NotificationCenter.default.addObserver(self, selector: #selector(onBlackListChangeNotificationHandler(_:)), name: .blackListChange, object: nil)
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        
        self.didEndScroll()
        
        // 判断是否需要展示弹窗
        if let userId = ARUserManager.shared.userId, !hasShowAlert {
            
            hasShowAlert = true
            var targetList: [String] = []
            if let list = UserDefaults.standard.array(forKey: Self.firstLoginUserKey) as? [String] {
                targetList.append(contentsOf: list)
            }
            if targetList.contains(where: {$0 == userId}) {
                // 已展示
                return
            }
            
            targetList.append(userId)
            UserDefaults.standard.set(targetList, forKey: Self.firstLoginUserKey)
            UserDefaults.standard.synchronize()
            
            onNoteBtnDidClick(noteBtn)
        }
    }
    
    // MARK: - UI
    
    private func setupUI() {
        // 要注意的是，需要计算Tabbar的高度
        view.addSubview(backgroundImageView)
        view.addSubview(coverImageView)
        view.addSubview(navView)
        view.addSubview(collectionView)
        view.addSubview(nextBtn)
        view.addSubview(noteContentView)
        view.addSubview(noteContentLabel)
        
        let bgImgScale = (backgroundImageView.image?.size.height ?? 1) / (backgroundImageView.image?.size.width ?? 1)
        backgroundImageView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.width.equalToSuperview()
            make.height.equalTo(view.snp.width).multipliedBy(bgImgScale)
        }
        
        coverImageView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.width.height.equalTo(view.snp.width)
        }
        
        navView.snp.makeConstraints { make in
            make.height.equalTo(44)
            make.left.right.equalToSuperview()
            make.top.equalToSuperview().offset(ARHelper.statusBarHeight())
        }
        
        collectionView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.height.equalTo(266)
            make.top.equalToSuperview().offset(ARHelper.heightScale(262))
        }
        
        nextBtn.snp.makeConstraints { make in
            make.width.equalTo(181)
            make.height.equalTo(72)
            make.right.equalToSuperview()
            make.centerY.equalTo(collectionView.snp.bottom).offset(-5)
        }
        
        noteContentView.snp.makeConstraints { make in
            make.height.equalTo(14)
            make.left.right.equalToSuperview()
            make.top.equalTo(nextBtn.snp.bottom).offset(ARHelper.heightScale(32))
        }
        
        noteContentLabel.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(40)
            make.right.equalToSuperview().offset(-40)
            make.top.equalTo(noteContentView.snp.bottom).offset(ARHelper.heightScale(16))
            make.bottom.lessThanOrEqualToSuperview().offset(-ARHelper.tabBarHeight())
        }
    }
    
    private func refreshUI() {
        self.collectionView.reloadData()
        self.didEndScroll()
    }
    
    // MARK: - Action
    
    @objc private func onPostBtnDidClick(_ sender: UIButton) {
        let vc = ARIndexPostViewController()
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    @objc private func onNextBtnDidClick(_ sender: UIButton) {
        
        // scrollToNext
        if (collectionView.jk.width <= 0 || viewScrolling) {
            return
        }
        
        let currentIndex = Int(collectionView.contentOffset.x / collectionView.jk.width) % viewModel.dataSource.count
        self.scrollToIndex(currentIndex + 1, animated: true)
    }
    
    @objc private func onNoteBtnDidClick(_ sender: UIButton) {
        
        let vc = ARIndexTipsAlertController.init()
        ARHelper.window().ar.topViewController()?.present(vc, animated: true)
    }
    
    @objc private func onBlackListChangeNotificationHandler(_ noti: Notification) {
        // 直接刷新
        self.refreshData()
    }
     
    // MARK: - Lazy
    
    private lazy var navView: UIView = {
        let view = UIView()
        view.backgroundColor = .clear
        
        view.addSubview(titleView)
        view.addSubview(postBtn)
        
        titleView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.top.equalToSuperview().offset(12)
        }
        
        postBtn.snp.makeConstraints { make in
            make.width.height.equalTo(30)
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().offset(-20)
        }
        
        return view
    }()
    
    private lazy var titleView: UIImageView = {
        let imageView = UIImageView(image: .init(named: "index_title"))
        return imageView
    }()
    
    private lazy var postBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setImage(.init(named: "index_post_icon"), for: .normal)
        btn.addTarget(self, action: #selector(onPostBtnDidClick(_:)), for: .touchUpInside)
        return btn
    }()
    
    private lazy var coverImageView: UIImageView = {
        let imageView = UIImageView()
        imageView.contentMode = .scaleAspectFill
        return imageView
    }()
    
    private lazy var backgroundImageView: UIImageView = {
        let imageView = UIImageView(image: .init(named: ""))
        return imageView
    }()
    
    private lazy var nextBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setImage(.init(named: "index_next_btn"), for: .normal)
        btn.addTarget(self, action: #selector(onNextBtnDidClick(_:)), for: .touchUpInside)
        return btn
    }()
    
    private lazy var noteContentView: UIView = {
        let contentView = UIView()
        
        let signShadowView = UIView()
        signShadowView.backgroundColor = UIColor(hexString: "#3ABBE9")
        signShadowView.layer.cornerRadius = 1
        
        let signView = UIView()
        signView.backgroundColor = UIColor(hexString: "#A6DEFF")
        signView.layer.cornerRadius = 1
        
        let noteLabel = UILabel()
        noteLabel.text = ARHelper.localString("Note")
        noteLabel.font = ARHelper.font(14, weight: .bold)
        noteLabel.textColor = .init(hexString: "#3ABBE9")
        
        contentView.addSubview(signShadowView)
        contentView.addSubview(signView)
        contentView.addSubview(noteLabel)
        contentView.addSubview(noteBtn)
        
        signView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(40)
            make.centerY.equalToSuperview().offset(-1)
            make.width.equalTo(22)
            make.height.equalTo(5)
        }
        
        signShadowView.snp.makeConstraints { make in
            make.left.equalTo(signView)
            make.width.equalTo(21)
            make.height.equalTo(4)
            make.top.equalTo(signView).offset(2)
        }
        
        noteLabel.snp.makeConstraints { make in
            make.centerY.equalToSuperview()
            make.left.equalTo(signView.snp.right).offset(8)
        }
        
        noteBtn.snp.makeConstraints { make in
            make.width.height.equalTo(14)
            make.centerY.equalToSuperview()
            make.left.equalTo(noteLabel.snp.right).offset(4)
        }
        
        return contentView
    }()
    
    private lazy var noteBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setImage(.init(named: "index_note_icon"), for: .normal)
        btn.addTarget(self, action: #selector(onNoteBtnDidClick(_:)), for: .touchUpInside)
        return btn
    }()
    
    private lazy var noteContentLabel: UILabel = {
        let label = UILabel()
        
        let text = ARHelper.localString("Welcome to view the recommended list of famous attractions! Let’s give thumbs up to the exciting and fun rafting attractions......")
        label.numberOfLines = 0
        label.attributed.text = "\(wrap: .init(string: text, .font(ARHelper.font(14, weight: .regular)), .foreground(.init(hexString: "#404040") ?? .black)), .paragraph(.alignment(.left), .maximumLineHeight(22), .minimumLineHeight(22)))"
        
        return label
    }()
    
    private lazy var collectionView: UICollectionView = {
        
        let flow = UICollectionViewFlowLayout()
        flow.itemSize = .init(width: ARHelper.screenWidth(), height: 266)
        flow.scrollDirection = .horizontal
        flow.minimumLineSpacing = 0
        flow.minimumInteritemSpacing = 0
        
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: flow)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(ARIndexWorkCell.self, forCellWithReuseIdentifier: Self.cellReuseId)
        
        collectionView.isPagingEnabled = true
        collectionView.backgroundColor = .clear
        return collectionView
    }()
}

extension ARIndexViewController: UICollectionViewDelegate, UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let index = indexPath.row % viewModel.dataSource.count
        let model = viewModel.dataSource[index]
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: Self.cellReuseId, for: indexPath) as! ARIndexWorkCell
        cell.work = model
        return cell
    }
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return viewModel.dataSource.count * 20
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let index = indexPath.row % viewModel.dataSource.count
        let model = viewModel.dataSource[index]
        
        // 进入详情页
        let vc = ARIndexWorkDetailController.init(workId: model.id)
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
}

extension ARIndexViewController: UIScrollViewDelegate {
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        self.didEndScroll()
    }
    
    func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
        self.didEndScroll()
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        viewScrolling = true
    }
    
    func didEndScroll() {
        // 获取当前index
        if (collectionView.jk.width <= 0) {
            return
        }
        if viewModel.dataSource.isEmpty {
            return
        }
        let currentIndex = Int(collectionView.contentOffset.x / collectionView.jk.width) % viewModel.dataSource.count
        self.scrollToIndex(currentIndex)
        
        let model = viewModel.dataSource[currentIndex]
        if let bundleName = model.coverPath,
           let path = Bundle.main.path(forResource: bundleName, ofType: nil) {
            self.coverImageView.ar.setImage(path)
        } else if let localPath = model.localCoverPath {
            self.coverImageView.ar.setImage(localPath)
        }
        
        viewScrolling = false
    }
    
    func scrollToIndex(_ index: Int, animated: Bool = false) {
        collectionView.scrollToItem(at: IndexPath(item: (viewModel.dataSource.count * 10 + index), section: 0), at: .right, animated: animated)
    }
}

extension ARIndexViewController: ARTabControllerRefresh {
    
    func refreshData() {
        // 刷新
        self.ar.showLoading()
        viewModel.fetchIndexWorks { [weak self] err in
            self?.ar.hideHUD()
            if let err = err {
                self?.ar.makeToast(err.localizedDescription)
                return
            }
            // 刷新
            self?.refreshUI()
        }
    }
}
